﻿#region "Copyright (C) Lenny Granovsky. 2005-2013"
//This program is free software distribute under the terms of the GNU General Public License as published by
//the Free Software Foundation. Please read AssemblyInfo.cs file for more information.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Web.Enhancements.Rest.Filters
{
    public class WebMethodFilter : IWebRestFilter
    {
        /// <summary>
        /// Gets or sets the HTTP Method as HttpMethodRequirement that is allowed for this method.
        /// </summary>
        public HttpMethodRequirement HttpMethod { get; set; }

        public WebMethodFilter()
        {
        }

        /// <summary>
        /// Method that is called prior the REST service handler created. This allows to cancel the call at earlier stages. 
        /// </summary>
        /// <remarks>The session and list parameters are not available at this time.</remarks>
        /// <param name="httpContext">Current HTTP content.</param>
        /// <param name="serviceContext">Current REST service context.</param>
        public void BeforeHandlerCreated(System.Web.HttpContext httpContext, IWebRestServiceContext serviceContext)
        {
            //verify the HTTP method requirement.
            string verb = httpContext.Request.HttpMethod.ToUpper();
            switch (verb)
            {
                case "GET":
                    if (this.HttpMethod == HttpMethodRequirement.GetOnly || this.HttpMethod == HttpMethodRequirement.GetOrPost)
                        return;
                    break;
                case "POST":
                    if (this.HttpMethod == HttpMethodRequirement.PostOnly || this.HttpMethod == HttpMethodRequirement.GetOrPost)
                        return;
                    break;
                case "PUT":
                    if (this.HttpMethod == HttpMethodRequirement.PutOnly)
                        return;
                    break;
                case "DELETE":
                    if (this.HttpMethod == HttpMethodRequirement.DeleteOnly)
                        return;
                    break;
            }
            throw new HttpException(System.Net.HttpStatusCode.MethodNotAllowed.GetHashCode(), string.Format(ErrorMessages.ResourceManager.GetString("HttpMethodNotAllowed"), serviceContext.MethodInfo.Name, verb));
        }

        public void BeforeMethodCall(System.Web.HttpContext httpContext, IWebRestServiceContext serviceContext)
        {
        }

        public void AfterMethodCall(System.Web.HttpContext context, ref object returnValue)
        {
        }
    }
}
